package com.zhansm.client;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class HttpUtil {


    private HttpUtil(){}

    public static void downloadFile(String httpurl,String downloadAddr) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        byte[] a = null;
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                String fileName =connection.getHeaderField("fileName");
                is = connection.getInputStream();
                a = new byte[is.available()];
                is.read(a);
                if (a.length<=0){
                    System.out.println("文件下载失败,请查看文件名是否正确");
                }else{
                    File file = new File(downloadAddr);
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    OutputStream outputStream = new FileOutputStream(downloadAddr+"\\"+fileName);
                    outputStream.write(a);
                    System.out.println("文件下载成功，请前往查看");
                    outputStream.close();
                }
            }else {
                System.out.println("文件下载失败,请检查文件名是否正确.");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }
    }

    public static String getFileData(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        byte[] a = null;
        String responseMessage= null;
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                byte[] b = new byte[is.available()];
                is.read(b);
                String s= new String(b, StandardCharsets.UTF_8);
                responseMessage = s;
            }else {
                System.out.println("文件数据获取失败,请检查文件名是否正确");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return responseMessage ;
    }

    /**
     *
     * @param httpUrl
     * @param fileAddr
     * @return
     * @throws Exception
     * 上传文件
     */
    public static String uploadFile(String httpUrl, String fileAddr) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(httpUrl);
            FileBody bin = new FileBody(new File(fileAddr));
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).build();
            httpPost.setEntity(reqEntity);
            CloseableHttpResponse response = null;
            String fileName = null;
            try {
                response = httpclient.execute(httpPost);
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state != 200) {
                    return null;
                }
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                fileName = jsonString;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (IOException var25) {
                    var25.printStackTrace();
                }

            }
            return fileName;
    }

}